#!/usr/bin/env node

/**
 * 快速测试MySQL MCP服务
 * 使用方法: node quick-test.js
 */

const fetch = require('node-fetch');

class QuickMCPTest {
  constructor(baseUrl = 'http://localhost:8099') {
    this.baseUrl = baseUrl;
    this.requestId = 0;
  }

  async callTool(name, args = {}) {
    const request = {
      jsonrpc: "2.0",
      id: (++this.requestId).toString(),
      method: "tools/call",
      params: { name, arguments: args }
    };

    try {
      const response = await fetch(`${this.baseUrl}/mcp/call`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(request)
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const result = await response.json();
      if (result.error) {
        throw new Error(`MCP错误: ${result.error.message}`);
      }
      return result.result;
    } catch (error) {
      throw new Error(`请求失败: ${error.message}`);
    }
  }

  async runTests() {
    console.log('🧪 MySQL MCP 服务测试\n');

    const tests = [
      {
        name: '测试连接',
        tool: 'test_connection',
        args: {}
      },
      {
        name: '获取表列表',
        tool: 'list_tables',
        args: {}
      },
      {
        name: '简单查询',
        tool: 'query',
        args: { sql: 'SELECT 1 as test' }
      },
      {
        name: '获取用户表结构',
        tool: 'describe_table',
        args: { table: 'sys_user' }
      }
    ];

    for (const test of tests) {
      try {
        console.log(`📋 ${test.name}...`);
        const result = await this.callTool(test.tool, test.args);
        console.log(`✅ 成功: ${JSON.stringify(result, null, 2).substring(0, 100)}...`);
      } catch (error) {
        console.log(`❌ 失败: ${error.message}`);
      }
      console.log('');
    }
  }
}

// 运行测试
async function main() {
  const tester = new QuickMCPTest();
  
  try {
    await tester.runTests();
    console.log('🎉 所有测试完成！');
    console.log('\n📋 如果所有测试都通过，说明MCP服务正常');
    console.log('🔧 如果Cursor还是无法连接，可能是Cursor的MCP功能问题');
  } catch (error) {
    console.error('❌ 测试失败:', error.message);
  }
}

main(); 